//
//  BRMShopInfoViewController.m
//  BrezzeSaaS
//
//  Created by IOS on 2022/3/11.
//  Copyright © 2022 Brezze GWG. All rights reserved.
//

#import "BRMShopInfoViewController.h"
#import "BRMInfoZeroTableViewCell.h"
#import "BRMImageEditViewController.h"
#import "BRMChangePhoneViewController.h"
#import "BRMapSearchViewController.h"
#import <GooglePlaces/GooglePlaces.h>
#import "TZImagePreviewController.h"
#import "BRAreaViewController.h"
#import "BRMInfoTopView.h"
#import "BRMInfoMidView.h"
#import "BRMInfoContactView.h"
#import "BRMInfoTImeView.h"
#import "BRIndustryPopView.h"
#import "BRMContactView.h"

@interface BRMShopInfoViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate,GMSAutocompleteViewControllerDelegate,BRMInfoTopViewDelegte>
{
    BRMInfoTopView *_topView;
    BRMInfoMidView *_midView;
    BRMInfoContactView *_infoView;
    BRMContactView *_contactView;
    BRMInfoTImeView *_timeView;
    UIScrollView *_scrollView;
    QMUIButton *_saveBtn;
    BOOL _hasEntRatio;
}

@property (nonatomic,strong) NSArray *imgDatas;

@property (nonatomic,strong) BRMInfoModel *infoModel;

@property (nonatomic,strong) BRIndustryPopView *industryView;

@end

@implementation BRMShopInfoViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setUI];

    [self requestInfo];
    
    [self.industryView requestList];
    
    [self bolckFunc];
    [self configModel];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
}

// 如果是游客限制编辑功能
- (void)isAdmin:(BOOL)isAdmin {
    
    _topView.userInteractionEnabled = isAdmin;
    _contactView.userInteractionEnabled = isAdmin;
    _timeView.userInteractionEnabled = isAdmin;
    _saveBtn.enabled = isAdmin;
}

- (void)configModel {
    if (self.branchId.length == 0) {
        BRMTimeDicJsonModel  *dto = [[BRMTimeDicJsonModel alloc] init];
        dto.check = NO;
        dto.businessHours = [NSMutableArray array];
        for (int i = 0; i < 7; i++) {
            BRMTimeJsonModel *model = [[BRMTimeJsonModel alloc] init];
            [dto.businessHours addObject:model];
        }
        _timeView.dto = dto;
        self.infoModel.openTime = dto.mj_JSONString; //设置默认
    }
}


#pragma mark - Request --
- (void)requestInfo {
    
    NSString *url = [NSString stringWithFormat:@"%@/%@",[BRAPI shopInfo],self.branchId];
    [[BRRequestManager shared] GET:url params:@{} succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        
        self.infoModel = [BRMInfoModel mj_objectWithKeyValues:dataDict[@"data"]];
        
        [self updateInfoData];
        
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        // 没有权限
        if (code == 21334) {
            WS(weakSelf);
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf.navigationController popToRootViewControllerAnimated:YES];
            });
        }
    }];
}

- (void)updateInfoData {
    
    BRMInfoModel *dto = self.infoModel;
    // ---------------
    _topView.logoURL = dto.logo;
//    _topView.shopName = dto.branchName;
    [self updateImags:dto.images];
    
    NSString *notset = @"--";
    // ---------------
    NSString *idStr = dto.branchCode.length != 0 ? dto.branchCode : notset;
    
    _midView.idStr = [NSString stringWithFormat:@"%@",idStr];

    if ([idStr isEqualToString:notset]) { //如果没id 取Noset
        _midView.statusStr = notset;
    }else {
        _midView.state = dto.state;
    }

    NSString *lanKey = [[[BRLanguageManager share] requestStr] lowercaseString];
    NSString *descriptionDicKey = lanKey;
    lanKey = [BRLanguageManager br_languageKey:lanKey inArr:[dto.industryName mj_keyValues].allKeys];
    descriptionDicKey = [BRLanguageManager br_languageKey:descriptionDicKey inArr:[dto.descriptionDic mj_keyValues].allKeys];
    NSString *title =  [dto.industryName valueForKey:lanKey];
    NSString *text =  [dto.descriptionDic valueForKey:descriptionDicKey];
    if (text.length != 0) {
        title = [NSString stringWithFormat:@"%@(%@)",title,text];
    }
    // ---------------
    [_infoView setTitle:dto.branchName by:0];
    [_infoView setTitle:title by:1]; //分类
    [_infoView setTitle:dto.addressMap by:2];
    [_infoView setTitle:dto.address by:3];

    [_infoView setTitle:BR_EmptyStr(dto.agentName) by:4]; //代理商
    [_infoView setTitle:[NSString stringWithFormat:@"%ld",dto.ratio] by:5]; //分成
    [_infoView setTitle:BR_EmptyStr(dto.billingTitle) by:6];
    _hasEntRatio = YES;
    
    [_contactView br_text:dto.principal by:0];
    [_contactView br_text:dto.phone by:1];
    [_contactView br_setOtp:dto.code by:1];
    NSString *account = dto.branchAccount.email;
    if (dto.branchAccount.phone.length != 0) {
        account = [NSString stringWithFormat:@"+%@ %@",dto.branchAccount.code,dto.branchAccount.phone];
    }
    [_contactView br_text:BR_EmptyStr(account) by:2];
    // ---------------
    if (dto.openTime.length != 0) {
        
        NSDictionary *dic = [dto.openTime mj_JSONObject];
        if (!BR_DictIsEmpty(dic)) {
            
            BRMTimeDicJsonModel *timedtos = [BRMTimeDicJsonModel mj_objectWithKeyValues:dic];
            _timeView.dto = timedtos;
            
        }
        
    }
    // 优先判断state状态 -》是否游客
//    BOOL isAdmin = dto.state == 1;
//    if (USERManager.userModel.visitor) isAdmin = NO;
//    [self isAdmin:isAdmin];
}

- (void)updateImags:(NSString *)images {
    if (!BR_StringIsEmpty(images)) {
        NSArray *imgs = [images componentsSeparatedByString:@","];
        [_topView updateImages:imgs];
    }else {
        [_topView updateImages:@[]];
    }
}

- (void)requestUpdate:(NSDictionary *)dic {
    [BRHud showInView:self.view];
    [[BRRequestManager shared] PUT:[BRAPI shopInfo] params:dic succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        [BRHud hiddenInView:self.view];
        NSLog(@"修改成功");
        if (self.editSuccBlock) self.editSuccBlock(self.infoModel.branchName);
        [BRHud showAuto:Localized(@"shop_saved") inView:self.view];
        WS(weakSelf);
        [self jk_performAfter:2 block:^{
            [weakSelf pop];
        }];
        
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        [BRHud hiddenInView:self.view];
    }];
}

#pragma mark - Func --
- (void)bolckFunc {
    
    WS(weakSelf);
    _topView.imgsBlock = ^{
        [weakSelf toImageVC];
    };
    _topView.logoBlock = ^{
        [weakSelf showSelectPhoto];
    };
    
    
    _infoView.contactTextChangBlock = ^(NSDictionary * _Nullable dic) {
        [weakSelf toChangParmas:dic];
    };
    _infoView.toMap = ^{
        [weakSelf toMap];
    };

    _infoView.toIndustryBlcok = ^{
        [weakSelf toIndustry];
    };

    
    _contactView.contactTextChangBlock = ^(NSDictionary * _Nullable dic) {
        [weakSelf toChangParmas:dic];
    };
    
    _contactView.toOtpBlock = ^{
        [weakSelf toCodePage];
    };
    
    _timeView.saveBlock = ^(NSDictionary * _Nullable dic) {
        [weakSelf toChangParmas:dic];
    };
    
    _timeView.switchOnBlock = ^(BOOL isOn) {
        
        [weakSelf toChangParmas:@{@"TimeOn":@(isOn)}];
        [weakSelf toScrollEdit:isOn];
    };
    
    self.industryView.selItemBlock = ^(NSDictionary *dic) {
    
        [weakSelf toChangParmas:dic];
        
    };
}

- (void)toScrollEdit:(BOOL)isOn {
   
    if (isOn) {
        [_timeView checkIsOn:isOn];
    }
    CGFloat time = isOn ? 0.2 : 0.0;
    CGFloat on_y = isOn ? (44 * 7 + 10) : 0; // 44+10 + 28
    CGFloat to_y = isOn ? _contactView.mj_y + _contactView.mj_h + 64 : (_timeView.mj_y + 72);
    CGFloat scroll_h =  kScreenHeight - kSafeAreaTopHeight;
    to_y =  to_y - scroll_h + on_y ;
    [self jk_performAfter:time block:^{
        [self->_scrollView setContentOffset:CGPointMake(0, to_y) animated:YES];
    }];
    
    if (!isOn) {
        [_timeView hiddenContentV:YES];
        [self jk_performAfter:0.3 block:^{
            [self->_timeView checkIsOn:isOn];
        }];
    }
   
}

- (void)toChangParmas:(NSDictionary *)dic {
    
    NSString *title = dic[@"title"];
    if ([title isEqualToString:Localized(@"shop_merchantName")]) {
        NSString *str = dic[@"text"];
        self.infoModel.branchName = str;
        
    }
    if ([title isEqualToString:Localized(@"shop_industryCategory")]) {

        NSString *lanKey = [[[BRLanguageManager share] requestStr] lowercaseString];
        
        NSString *title =  dic[@"text"];
        NSString *text =  dic[@"textSub"];
        [self.infoModel.industryName setValue:title forKey:lanKey];
        [self.infoModel.descriptionDic setValue:text forKey:lanKey];
        self.infoModel.industryId = dic[@"industryId"];
        
        if (text.length != 0) {
            title = [NSString stringWithFormat:@"%@(%@)",title,text];
        }
        [_infoView setTitle:title by:1]; //分类
        
        return;
    }
    if ([title isEqualToString:Localized(@"shop_location")]) {
        self.infoModel.lat = [dic[@"lat"] floatValue];
        self.infoModel.lng = [dic[@"lng"] floatValue];
//        self.infoModel.address = dic[@"text"];
        self.infoModel.addressMap = dic[@"text"];
    }
    if ([title isEqualToString:Localized(@"shop_address")]) {

        self.infoModel.address = dic[@"text"];
    }
    // 使用代理商同一控件 使用判断
    if ([title isEqualToString:Localized(@"shop_contactNum")] || [title isEqualToString:Localized(@"shop_contactPerson")]) {

        self.infoModel.phone = dic[@"text"];
    }
    if ([title isEqualToString:Localized(@"shop_shopPhoto")]) {

        NSString *imgs = dic[@"text"];
        self.infoModel.images = imgs ;
        [self updateImags:imgs];
    }
    if ([title isEqualToString:Localized(@"openTime")]) {

        self.infoModel.openTime = dic[@"text"];
    }
    if ([title isEqualToString:Localized(@"headIcon")]) {

        self.infoModel.logo = dic[@"text"];
    }
    
    if ([title isEqualToString:@"TimeOn"]) {

    }
    if ([title isEqualToString:Localized(@"shop_profitAllocation")]) {
        NSString *text = dic[@"text"];
        self.infoModel.ratio = [text integerValue];
        _hasEntRatio = text.length != 0;
    }
    if ([title isEqualToString:Localized(@"shop_franchisee")]) {
        NSString *text = dic[@"text"];
        NSString *idText = dic[@"principalId"];
        self.infoModel.agentName = text;
        self.infoModel.agentId = idText;
        [_infoView setTitle:text by:4]; //代理商
        
    }
    if ([title isEqualToString:Localized(@"shop_inCharge")]) {
        self.infoModel.principal = dic[@"text"];
        return;
    }
    if ([title isEqualToString:Localized(@"shop_pricePlan")]) {
        NSString *text = dic[@"text"];
        NSString *idText = dic[@"billingId"];
        self.infoModel.billingTitle = text;
        self.infoModel.billingId = idText.integerValue;
        [_infoView setTitle:text by:6]; //计费规则
        return;
    }
}

- (void)toImageVC {
    
    
    BRMImageEditViewController *vc = [[BRMImageEditViewController alloc] init];
    
    [self.navigationController pushViewController:vc animated:YES];
    if (!BR_StringIsEmpty(self.infoModel.images)) {
        NSArray *imgs = [self.infoModel.images componentsSeparatedByString:@","];
        vc.imgs = imgs;
    }
    WS(weakSelf);
    vc.updateImgsBlock = ^(NSDictionary * _Nullable dic) {
        [weakSelf toChangParmas:dic];
    };
}

- (void)toIndustry {
    
    [self.industryView show];
}


- (void)toMap {
    
    GMSAutocompleteViewController *acController = [[GMSAutocompleteViewController alloc] init];
        acController.delegate = self;
    acController.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:acController animated:YES completion:nil];
}

- (void)cellDidSel:(NSIndexPath *)indexP {
    
    NSInteger secction = indexP.section;
    NSInteger row = indexP.row;
    if (secction == 0) {
        if (row == 1) {
            
            return;
        }
        
        return;
    }
    
    if (secction == 2) {
        
        
        BRMChangePhoneViewController *vc = [[BRMChangePhoneViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        
        return;
    }
    
}

- (void)toSave:(QMUIButton *)btn {
    
//    if (self.infoModel.logo.length == 0) {
//        [BRHud show:Localized(@"toast_uploadLogo") inView:self.view];
//        return;
//    }
    [self.view endEditing:YES];
    
    if (self.branchId.length == 0) return;
    if (self.infoModel.branchName.length == 0) {
        [BRHud show:Localized(@"shop_hintShopName") inView:self.view];
        return;
    }
    if (self.infoModel.industryId.length == 0) {
        [BRHud show:Localized(@"shop_hintSelectType") inView:self.view];
        return;
    }
    if (self.infoModel.addressMap.length == 0) {
        [BRHud show:Localized(@"shop_hintMapLocation") inView:self.view];
        return;
    }
    if (self.infoModel.address.length == 0) {
        [BRHud show:Localized(@"shop_hintAddress") inView:self.view];
        return;
    }
    if (self.infoModel.principal.length == 0) {
        [BRHud show:Localized(@"shop_hintInCharge") inView:self.view];
        return;
    }
    if (self.infoModel.phone.length == 0) {
        [BRHud show:Localized(@"shop_hintContact") inView:self.view];
        return;
    }
    if (self.infoModel.code == 0) {
        self.infoModel.code = 39; // 默认86
    }
    // 先转换成dic，再用指定model获取需要的请求参数，再转换成reqDic
    NSDictionary *dic = [self.infoModel mj_keyValues];
    // 参数过滤（↓）
    BRMInfoRequestModel *req = [BRMInfoRequestModel mj_objectWithKeyValues:dic];
    NSDictionary *reqDic = [req mj_keyValues];
    NSMutableDictionary *dicMut = [NSMutableDictionary dictionaryWithDictionary:reqDic];
    
    [dicMut setValue:self.branchId forKey:@"id"];
//    NSLog(@"mj_JSONString - \n%@\n【\n%@\n】",dicMut,[dicMut mj_JSONString]);
    [self requestUpdate:dicMut];
}

- (void)showSelectPhoto {
    
    /**
     *  弹出提示框
     */
    //初始化提示框
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    //按钮：从相册选择，类型：UIAlertActionStyleDefault
    [alert addAction:[UIAlertAction actionWithTitle: Localized(@"public_album") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [GGPermissionsManage checkPhotosOpenPer:^{
            //初始化UIImagePickerController
            UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
            //获取方式1：通过相册（呈现全部相册），UIImagePickerControllerSourceTypePhotoLibrary
            //获取方式2，通过相机，UIImagePickerControllerSourceTypeCamera
            //获取方法3，通过相册（呈现全部图片），UIImagePickerControllerSourceTypeSavedPhotosAlbum
            PickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            //允许编辑，即放大裁剪
            PickerImage.allowsEditing = YES;
            //自代理
            PickerImage.delegate = self;
            PickerImage.modalPresentationStyle = UIModalPresentationFullScreen;
            //页面跳转
            [self presentViewController:PickerImage animated:YES completion:nil];
        } faile:^{
            
        }];
        
    }]];
    //按钮：拍照，类型：UIAlertActionStyleDefault
    [alert addAction:[UIAlertAction actionWithTitle: Localized(@"public_camera") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
        /**
         其实和从相册选择一样，只是获取方式不同，前面是通过相册，而现在，我们要通过相机的方式
         */
        [GGPermissionsManage checkCameraPer:^{
            UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
            //获取方式:通过相机
            PickerImage.sourceType = UIImagePickerControllerSourceTypeCamera;
            PickerImage.allowsEditing = YES;
            PickerImage.delegate = self;
            PickerImage.modalPresentationStyle = UIModalPresentationFullScreen;
            [self presentViewController:PickerImage animated:YES completion:nil];
        } faile:^{
            
        }];
        
    }]];
    //按钮：取消，类型：UIAlertActionStyleCancel
    [alert addAction:[UIAlertAction actionWithTitle: Localized(@"public_cancel") style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}


- (void)toCodePage {
    BRAreaViewController *vc = [[BRAreaViewController alloc] init];
    
    [self.navigationController pushViewController:vc animated:YES];
    WS(weakSelf);
    vc.selectCodeBlock = ^(NSInteger code) {
//        NSString *codeStr = [NSString stringWithFormat:@"%ld",code];
        weakSelf.infoModel.code = code;
        [self->_contactView br_setOtp:code by:1];
    };
}

#pragma mark - GooglePlace delegate --
- (void)viewController:(GMSAutocompleteViewController *)viewController didAutocompleteWithPlace:(GMSPlace *)place {
    
    NSLog(@"%@ - lng %.2f - lat %.2f \n address - %@ [%@]",place.name,place.coordinate.longitude,place.coordinate.latitude,place.addressComponents,place.formattedAddress);
    
    [self toChangParmas:@{@"text":place.formattedAddress,@"title":Localized(@"shop_location"),@"lng":@(place.coordinate.longitude),@"lat":@(place.coordinate.latitude)}];
    [_infoView setTitle:place.formattedAddress by:2];
//    [_contactView setTitle:place.formattedAddress by:3];
    
    [self dismissPlaceVC:viewController];
    
}

- (void)viewController:(GMSAutocompleteViewController *)viewController didFailAutocompleteWithError:(NSError *)error {
    
    [BRHud showAuto:@"Map error" inView:self.view];
    [self dismissPlaceVC:viewController];
}

- (void)wasCancelled:(GMSAutocompleteViewController *)viewController {
    // 取消
    [self dismissPlaceVC:viewController];;
}


- (void)dismissPlaceVC:(GMSAutocompleteViewController *)viewController {
    [viewController dismissViewControllerAnimated:YES completion:^{

    }];
//    [viewController.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UINavigationControllerDelegate, UIImagePickerControllerDelegate
//PickerImage完成后的代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    //定义一个newPhoto，用来存放我们选择的图片。
    UIImage *newPhoto = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    // 压缩需要上传的图片
    UIImage *uploadImage = [self imageWithImageSimple:newPhoto scaledToSize:CGSizeMake(255, 255)];
    NSData *uploadData = UIImageJPEGRepresentation(uploadImage, 1);
    [self uploadHeader: uploadData];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)uploadHeader:(NSData*)data{
    
    [BRHud showHud];
//    WS(weakSelf);
    [BRAPI uploadFiles:data beginBlock:^{

    } successBlock:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSMutableDictionary *dic  = [NSMutableDictionary dictionaryWithDictionary:@{}];
        
        NSInteger code = [responseObject[@"code"] integerValue];
        if (code != 0) {
            [BRHud hidden];
            NSLog(@"%@",responseObject[@"message"])
            return;
        }
        NSString *logoURL = responseObject[@"data"][@"value"];
        dic[@"icon"] = logoURL;
        
        self->_topView.logoURL = logoURL;
        
        [self toChangParmas:@{@"title":@"headIcon",@"text":logoURL}];
 
            [BRHud hidden];

    } failureBlock:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [BRHud hidden];
    }];
    
    
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
//压缩图片
- (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    // End the context
    UIGraphicsEndImageContext();
    // Return the new image.
    return newImage;
}

#pragma mark - BRMInfoTopViewDelegte --
- (void)clickImg:(NSInteger)index imageView:(UIImageView *)imgView data:(NSArray *)imgs {
    //图片点击
    self.imgDatas = imgs;
    [self clickImg:index imageView:imgView];
}

#pragma mark - img picker --
- (void)clickImg:(NSInteger)index imageView:(nonnull UIImageView *)logImgView {
    
    TZImagePickerController *imagePickerVc = [self createTZImagePickerController];
    imagePickerVc.maxImagesCount = 1;
    imagePickerVc.showSelectBtn = NO;
    [imagePickerVc setPhotoPreviewPageDidLayoutSubviewsBlock:^(UICollectionView *collectionView, UIView *naviBar, UIButton *backButton, UIButton *selectButton, UILabel *indexLabel, UIView *toolBar, UIButton *originalPhotoButton, UILabel *originalPhotoLabel, UIButton *doneButton, UIImageView *numberImageView, UILabel *numberLabel) {
        if (naviBar) {
            [naviBar removeFromSuperview];
            naviBar = nil;
        }
        if (backButton) {
            [backButton removeFromSuperview];
            backButton = nil;
        }
        if (numberLabel) {
            [numberLabel removeFromSuperview];
            numberLabel = nil;
        }
        if (toolBar) {
            [toolBar removeFromSuperview];
            toolBar = nil;
        }
        if (numberImageView) {
            [numberImageView removeFromSuperview];
            numberImageView = nil;
        }
        if (doneButton) {
            [doneButton removeFromSuperview];
            doneButton = nil;
        }
    }];
    
    NSArray *urlArr = [self.imgDatas mutableCopy];
    TZImagePreviewController *previewVc = [[TZImagePreviewController alloc] initWithPhotos:urlArr currentIndex:index tzImagePickerVc:imagePickerVc];
    [previewVc setBackButtonClickBlock:^(BOOL isSelectOriginalPhoto) {
        NSLog(@"预览页 返回 isSelectOriginalPhoto:%d", isSelectOriginalPhoto);
    }];
    

    [previewVc setSetImageWithURLBlock:^(NSURL *URL, UIImageView *imageView, NSInteger index, void (^completion)(void)) {
        [self configImageView:imageView URL:URL index:index completion:completion];
    }];
    
    [previewVc setDoneButtonClickBlock:^(NSArray *photos, BOOL isSelectOriginalPhoto) {
        
        NSLog(@"预览页 完成 isSelectOriginalPhoto:%d photos.count:%zd", isSelectOriginalPhoto, photos.count);
    }];
    
    previewVc.updateCurreIndex = ^(NSInteger index) {
        [self->_topView.myCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    };
    
    [self scaleOfCell:logImgView text:@"" VC:previewVc];
    
    WS(weakSelf);
    previewVc.signOutBlock = ^(UIImageView *imageView, NSInteger cureIndex) {
        
        [weakSelf scaleOfVCImage:imageView index:cureIndex cellIndex:0];
    };
}

- (void)scaleOfCell:(UIImageView *)image text:(NSString *)text VC:(TZImagePreviewController *)previewVc{
    
    __block UIImageView *imageView = [[UIImageView alloc] initWithFrame:[image convertRect: image.bounds toView:image.window]];
    imageView.backgroundColor = [UIColor blackColor];
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.alpha = 0;
    [self.view addSubview:imageView];
    UIImage *imageN = image.image;
    imageView.image = imageN;
    [UIView animateWithDuration:0.3 animations:^{
        imageView.frame = self.view.bounds;
        if (imageView.image.size.height/imageView.image.size.width < kScreenHeight / kScreenWidth) {
            imageView.frame = CGRectMake(0, (kScreenHeight - imageView.image.size.height * (kScreenWidth / imageView.image.size.width)) / 2, kScreenWidth, imageView.image.size.height * (kScreenWidth / imageView.image.size.width));
        }else{
            
            imageView.frame = CGRectMake((kScreenWidth - imageView.image.size.width * (kScreenHeight / imageView.image.size.height)), 0, imageView.image.size.width * (kScreenHeight / imageView.image.size.height), kScreenHeight);
        }
        imageView.alpha = 1;
    } completion:^(BOOL finished) {
        [imageView removeFromSuperview];
        imageView = nil;
        [self pushViewController:previewVc animated:NO completion:^{
            
        }];
    }];
}

- (void)scaleOfVCImage:(UIImageView *)image index:(NSInteger)index cellIndex:(NSInteger)cellIndex {
    
    __block UIImageView *imageView = [[UIImageView alloc] initWithFrame:[image convertRect: image.bounds toView:image.window]];
    imageView.frame = self.view.bounds;
    imageView.backgroundColor = [UIColor blackColor];
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.alpha = 1;
    [self.view addSubview:imageView];
    imageView.image = image.image;
    
    [_topView.myCollectionView layoutIfNeeded];//横向布局，图片移动到指定图片后 需layoutIfNeeded，获取cell的准确位置
    BRStationImgCollectionViewCell *cell = (BRStationImgCollectionViewCell *)[_topView.myCollectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0]];
    
    CGRect frame = [cell.img convertRect:cell.img.bounds toView:self.view];
    [UIView animateWithDuration:0.3 animations:^{

        imageView.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, frame.size.height);
        imageView.alpha = 0;
    } completion:^(BOOL finished) {
        [imageView removeFromSuperview];
        imageView = nil;
        
    }];
}

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated completion: (void (^)(void))completion {
    [CATransaction setCompletionBlock:completion];
    [CATransaction begin];
    [self.navigationController pushViewController:viewController animated:animated];
    [CATransaction commit];
}

- (void)configImageView:(UIImageView *)imageView URL:(NSURL *)URL index:(NSInteger)index completion:(void (^)(void))completion{
    if ([URL.absoluteString.lowercaseString hasSuffix:@"gif"]) {
        // 先显示静态图占位
        [[SDWebImageManager sharedManager] loadImageWithURL:URL options:0 progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
            if (!imageView.image) {
                imageView.image = image;
            }
        }];
        // 动图加载完再覆盖掉
        [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:URL options:0 progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
            imageView.image = [UIImage sd_imageWithGIFData:data];
            if (completion) {
                completion();
            }
        }];
    } else {
        NSArray *urlArr = [self.imgDatas mutableCopy];
        NSString *url = urlArr[index];
        UIImage *image =  (UIImage *)[[SDImageCache sharedImageCache] imageFromCacheForKey:url];
        if (!image) {
            //展开后没有缓存优先显示默认图片
            image = UIImageMake(kDefaultImg);
        }
        [imageView sd_setImageWithURL:URL placeholderImage:image completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
            if (completion) {
                completion();
            }
        }];
    }
}

#pragma mark - TZImagePickerController

- (TZImagePickerController *)createTZImagePickerController {
    [TZImageManager manager].isPreviewNetworkImage = YES;
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 columnNumber:4 delegate:self pushPhotoPickerVc:NO];
    
#pragma mark - 个性化设置，这些参数都可以不传，此时会走默认设置
    imagePickerVc.isSelectOriginalPhoto = NO;
    imagePickerVc.iconThemeColor = [UIColor colorWithRed:31 / 255.0 green:185 / 255.0 blue:34 / 255.0 alpha:1.0];

    imagePickerVc.allowPickingVideo = YES;
    imagePickerVc.allowPickingImage = YES;
    imagePickerVc.allowPickingOriginalPhoto = YES;
    imagePickerVc.allowPickingGif = YES;
    imagePickerVc.showSelectedIndex = YES;
    imagePickerVc.allowPickingMultipleVideo = YES;
    imagePickerVc.needShowStatusBar = YES;
    imagePickerVc.showSelectBtn = NO;
    
    return imagePickerVc;
}
#pragma mark - UI --
- (void)setUI {
    
 
    
    BRNavView *top = [self br_createTop:Localized(@"shop_merchantDetail")];
    
    
    QMUIButton *editBtn = [[QMUIButton alloc] init];
    [editBtn setTitle:Localized(@"shop_save") forState:UIControlStateNormal];
    editBtn.titleLabel.font = [UIFont fontM:17];
    [editBtn setTitleColor:kColorTitle forState:UIControlStateNormal];
    [editBtn setTitleColor:kColorTitle66B forState:UIControlStateDisabled];
    [top.topView addSubview:editBtn];
    [editBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(kNavH);
        make.bottom.offset(0);
        make.right.offset(-28);
    }];
    [editBtn addTarget:self action:@selector(toSave:) forControlEvents:UIControlEventTouchUpInside];
    _saveBtn = editBtn;
    
    self.view.backgroundColor = UIColor.qd_backgroundColorLighten;
    UIScrollView *sView = [[UIScrollView alloc] init];
    sView.showsHorizontalScrollIndicator = NO;
    sView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:sView];
    [sView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.offset(0);
        make.top.offset(kSafeAreaTopHeight);
    }];
    _scrollView = sView;
    
    BRMInfoTopView *topView = [[BRMInfoTopView alloc] init];
    topView.delegate = self;
    [sView addSubview:topView];
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(kScreenWidth - 32);
        make.top.offset(10);
        make.left.offset(16);
        make.right.offset(-16);
    }];
    
    BRMInfoMidView *midView = [[BRMInfoMidView alloc] init];
    [sView addSubview:midView];
    [midView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(topView.mas_bottom).offset(10);
        make.left.offset(16);
        make.right.offset(-16);
    }];
    
    BRMInfoContactView *infoView = [[BRMInfoContactView alloc] init];
    [sView addSubview:infoView];
    [infoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(midView.mas_bottom).offset(10);
        
        make.left.offset(16);
        make.right.offset(-16);
    }];
    
    BRMContactView *contactView = [[BRMContactView alloc] init];
    contactView.titleL.text = Localized(@"shop_contactPerson");
    [sView addSubview:contactView];
    [contactView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(infoView.mas_bottom).offset(10);
        make.left.offset(16);
        make.right.offset(-16);
    }];
    
    BRMInfoTImeView *timeView = [[BRMInfoTImeView alloc] init];
    [sView addSubview:timeView];
    [timeView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(contactView.mas_bottom).offset(10);
        make.left.offset(16);
        make.right.offset(-16);
        make.bottom.offset(-(28 + kSafeAreaBottomHeight));
    }];
    
    _topView = topView;
    _midView = midView;
    _infoView = infoView;
    _contactView = contactView;
    _timeView = timeView;
    
    self.industryView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    [self.view addSubview:self.industryView];
    
    
    return;
}

- (BRIndustryPopView *)industryView {
    
    if (_industryView == nil) {
        
        _industryView = [[BRIndustryPopView alloc] init];
    }
    return _industryView;
}

- (BOOL)forceEnableInteractivePopGestureRecognizer {
    // 屏蔽右滑返回
    return NO;

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
